//
//  FMDBTool.m
//  SiriShortCutDemo
//
//  Created by zxy on 2019/11/25.
//  Copyright © 2019 zxy. All rights reserved.
//

#import "FMDBTool.h"
#import "FMDatabase.h"
#import "FMDB.h"


static FMDatabase *db;

@implementation FMDBTool

+ (void)initialize {
    //拼接数据库文件保存路径
    NSString *fileName = [[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.testDemo.Siri"] absoluteString] stringByAppendingFormat:@"QuickDB.sqlite"];
    // 创建数据库对象
    FMDatabase *datebase = [FMDatabase databaseWithPath:fileName];
    db = datebase;
    
    BOOL openSuccess = [datebase open];
    
    if (openSuccess) {
        NSLog(@"数据库打开成功");
        //创建数据库表
        NSString *sql = @"create table if not exists t_BaiSi (ID integer primary key,name text);";
        BOOL success = [db executeUpdate:sql];
        if (success) {
            NSLog(@"创建表成功");
        }else{
            NSLog(@"创建表失败");
        }
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
}


+ (void)saveCoffee:(CoffeeModel *)coffee {
    NSString *sql = [NSString stringWithFormat:@"insert into t_BaiSi (ID,name) values (%ld,'%@');",coffee.ID,coffee.name];
    
    if ([db executeUpdate:sql]) {
        NSLog(@"添加成功");
    }else{
        NSLog(@"添加失败");
    }
}

+ (NSMutableArray *)allCoffees {
    NSMutableArray *coffeeArr = [NSMutableArray array];
    NSString *sql;
    //查找全部
    sql = @"select * from t_BaiSi order by ID desc";
    
    // 查询的结果集
    FMResultSet *result = [db executeQuery:sql];
    if ([db executeQuery:sql]) {
        NSLog(@"查找成功");
    }else{
        NSLog(@"查找失败");
    }
    while ([result next]) {
        // 包装成模型
        CoffeeModel *coffee = [[CoffeeModel alloc] init];
        coffee.ID = [[result stringForColumn:@"ID"] integerValue];
        coffee.name = [result stringForColumn:@"name"];
        
        [coffeeArr addObject:coffee];
        
    }
    return coffeeArr;
}
@end
